import { ItemTypes } from "@/data/pages/pagesTypes";
import { useApplicationInfo } from "@/store/applicationDataContext";
import { useAuth } from "@/store/authContext";
import {
  addRemoveUserFav,
  placeOrder,
  addUserCart,
  addToLineUp,
  useUserInfo,
  requestSubscribeMessage
} from "@/store/userDataContext";
import { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { navigateTo } from "@/utils/navigation";
import notifications from "@/data/notifications";
import { ActionNames, sendAction } from "@/utils/tracking";

export default function useDetailPageData<EntityType>(type: ItemTypes) {
  const [detailPageData, setDetailPageData] = useState<null | EntityType>();
  const { getSingleDetailPage } = useApplicationInfo();
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData } = userInfoState;
  const { dispatchAuthAction } = useAuth();
  const [liked, setLiked] = useState(false);
  const [preview, setPreview] = useState(false);
  const { params } = useRouter();

  const handleFav = async (id, type) => {
    const changedLike = await addRemoveUserFav({
      query: {
        mainId: id,
        type: type,
      },
      authDispatch: dispatchAuthAction,
    });
    changedLike && sendAction(ActionNames.DetailLikeClick)
    setLiked(changedLike);
  };

  const handlePlaceOrder = async (misc: any) => {
    const preOrderNo = await placeOrder({
      query: misc.query,
      authDispatch: dispatchAuthAction,
    });
    if (preOrderNo) {
      navigateTo(`pages/checkout/index?preOrderNo=${preOrderNo}`);
    }
  };

  const handleAddtoCart = async (misc: any) => {
    if (userData) {
      return await addUserCart(dispatchUserDataAction, userData, misc);
    }
  };

  const handleLineUp = async (misc: any) => {
    requestSubscribeMessage([notifications.lineUp.success]);
    return await addToLineUp(misc);
  };

  useEffect(() => {
    const fetchData = async () => {
      if (params.id) {
        const detailData = (await getSingleDetailPage(
          type,
          +params.id
        )) as unknown as any;
        if (detailData) {
          detailData.handleFav = handleFav;
          detailData.handlePlaceOrder = handlePlaceOrder;
          detailData.handleAddtoCart = handleAddtoCart;
          detailData.handleLineUp = handleLineUp;
          setLiked(detailData.isCollection);
          setDetailPageData(detailData);
        }
      }
    };
    if (params.type === "preview") {
      setPreview(true);
    }
    fetchData();
  }, []);

  return [detailPageData, liked, preview];
}
